package cn.toolck.minitomcat.start;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/*
 * 需求进行http请求并相应"你好"
 *
 * */
public class Starter_0_1 extends AbstractStarter implements Starter {

    @Override
    public void init() {

    }

    @Override
    public void start() {
        try {
            ServerSocket serverSocket = new ServerSocket(8081);
            while (true) {
                Socket socket = serverSocket.accept();
                InputStream in = socket.getInputStream();
                OutputStream out = socket.getOutputStream();
                int num = 0;
                StringBuilder requestStr = new StringBuilder();
                while (num == 0) {
                    num = in.available();
                }
                byte[] bytes = new byte[num];
                requestStr.append(new String(bytes));
                StringBuilder responseStr = new StringBuilder();
                String body = "<h1>你好</h1>";
                responseStr.append("HTTP/1.1 200 OK\n")
                        .append("Content-Type: text/html;charset=utf-8\n")
                        .append("Content-Length:" + body.length() + "\n")
                        .append("\r\n")
                        .append(body);
                out.write(responseStr.toString().getBytes());
                out.flush();
                System.out.println(responseStr);
                //关闭
                out.close();
                in.close();
                socket.close();
            }
        } catch (
                Exception e) {
            e.printStackTrace();
        }
    }

}
